package json;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import json.Province;

import java.net.URLEncoder;
import java.nio.charset.Charset;


/**
 * @Description TODO
 * @Author hhy
 * @Date 2020/10/21 16:17
 */
public class Weather {


    public String getWeather(String city){
        String province = Province.getProvinceByCity(city);
        if (province==null) return null;
        province = URLEncoder.encode(province, Charset.forName("UTF-8"));
        String cityUrl = URLEncoder.encode(city, Charset.forName("UTF-8"));
        String url = "https://wis.qq.com/weather/common?source=pc&weather_type=observe%7Cindex%7Calarm%7Climit%7Ctips%7Crise&province="+province+"&city="+cityUrl;
        String s = HttpUtil.get(url);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        Long status = jsonObject.getLong("status");
        //如果这个请求发送成功了，那就继续
        if (status == 200){
            JSONObject data = jsonObject.getJSONObject("data");
            JSONObject observe = data.getJSONObject("observe");
            JSONObject index = data.getJSONObject("index");
            JSONObject cold = index.getJSONObject("cold");

            String weatherString = StrUtil.format("{}今天的天气是{}，当前温度为{}°C，{}",city,observe.getStr("weather"),observe.getStr("degree"),cold.getStr("detail"));
            return weatherString;
        }

        return null;
    }
}
